package me.firstapp.weixin.controller.cash;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.common.utils.SystemConfig;
import me.firstapp.common.utils.WeiXinConfig;
import me.firstapp.module.weixin.cash.CashApply;
import me.firstapp.module.weixin.jinbi.JinBiAccount;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.system.ThisSystem;
import me.firstapp.service.weixin.account.JinBiAccountService;
import me.firstapp.service.weixin.cash.CashApplyService;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.service.weixin.system.ThisSystemService;
import me.firstapp.weixin.controller.base.BaseController;

@Controller
public class CashController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(CashController.class);

	@Autowired
	private MemberService memberService;

	@Autowired
	private CashApplyService cashApplyService;

	@Autowired
	private JinBiAccountService jinBiAccountService;

	@Autowired
	private ThisSystemService thisSystemService;

	@Autowired
	private WeixinProxy weixinProxy;

	@RequestMapping("/page/cashApplyPage.htm")
	public ModelAndView showCashApplyPage(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		if (null == member) {
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		JinBiAccount jinBiAccount = jinBiAccountService.findJinBiAccountByCardNoAndOpenId(member.getCardNo(), openId);
		modelMap.put("jinBiBalance", jinBiAccount.getBalance());
		int a = (int) (jinBiAccount.getBalance().doubleValue() / 100 * 100);
		int b = a % 100;
		int money = a - b;
		modelMap.put("money", money);
		ThisSystem thisSystem = thisSystemService.findThisSystem();
		BigDecimal rate = thisSystem.getCashFeeRate();
		modelMap.put("rate", rate.multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).intValue() + "%");
		BigDecimal transferFee = new BigDecimal(money).multiply(rate).setScale(2, RoundingMode.HALF_UP);
		modelMap.put("transferFee", transferFee);
		BigDecimal actualCashAmount = new BigDecimal(money).subtract(transferFee).setScale(2, RoundingMode.HALF_UP);
		modelMap.put("actualCashAmount", actualCashAmount);
		return new ModelAndView("cash/cashApply", modelMap);
	}

	@RequestMapping(value = "page/cashApply.do", method = RequestMethod.POST)
	public void cashApply(String contact, String realName, String aliAccount, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			if (StrUtils.isNULL(contact)) {
				throw new ServiceException("error", "联系方式不能为空");
			}
			if (StrUtils.isNULL(realName)) {
				throw new ServiceException("error", "真实姓名不能为空");
			}
			if (StrUtils.isNULL(aliAccount)) {
				throw new ServiceException("error", "支付宝帐号不能为空");
			}
			String openId = super.getCurrentLoginOpenId(request, response);
			CashApply cashApply = cashApplyService.executeAddCashApply(openId, contact, realName, aliAccount);
			try {
				TemplateMessage tplMessage = new TemplateMessage(openId, WeiXinConfig.WEIXIN_CASH_APPLY_TEMPLATE_ID,
						SystemConfig.mServerUrl + "/page/cashApplyRecordPage.htm");

				Member member = memberService.findMemberByOpenId(openId);
				String remark = "【重要】请及时联系客服，提供您的ID（" + member.getCardNo() + "）和提现申请编号（" + cashApply.getCashNo()
						+ "），以便客服快速审核通过。提现客服微信号：1046566144";
				tplMessage.pushHead("").pushTail("").pushItem("first", "你好,提现申请已经收到")
						.pushItem("keyword1", member.getName())
						.pushItem("keyword2", DateUtils.getNowStr("yyyy-MM-dd HH:mm:ss"))
						.pushItem("keyword3",
								"￥" + cashApply.getActualCashAmount().setScale(2, RoundingMode.HALF_UP).doubleValue())
						.pushItem("keyword4", "微信").pushItem("remark", remark);
				TmplApi tmplApi = new TmplApi(weixinProxy.getTokenManager());
				String sendResult = tmplApi.sendTmplMessage(tplMessage);
				System.out.println("消息模板【" + WeiXinConfig.WEIXIN_CASH_APPLY_TEMPLATE_ID + "】发送消息返回结果：" + sendResult);
				logger.info("消息模板【" + WeiXinConfig.WEIXIN_CASH_APPLY_TEMPLATE_ID + "】发送消息返回结果：" + sendResult);
			} catch (WeixinException e) {
				e.printStackTrace();
				logger.error("提现申请通知发送失败", e);
			}
			result.setObject(cashApply);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
			logger.error("提现申请失败", e);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
			logger.error("提现申请失败", e);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/cashSuccessPage.htm")
	public ModelAndView showCashSuccessPage(String cashNo, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		String openId = super.getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		modelMap.put("cashNo", cashNo);
		modelMap.put("cardNo", member.getCardNo());
		return new ModelAndView("cash/cashSuccess", modelMap);
	}

	@RequestMapping("/page/cashApplyRecordPage.htm")
	public ModelAndView showCashApplyRecordPage(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		BigDecimal totalAmount = cashApplyService.findMemberTotalCashAmount(openId, member.getCardNo());
		modelMap.put("totalAmount", totalAmount);
		return new ModelAndView("cash/cashApplyRecord", modelMap);
	}

	@RequestMapping("/page/getCashApplyData.do")
	public void getCashApplyData(@RequestParam(defaultValue = "1") int pageIndex,
			@RequestParam(defaultValue = "20") int pageSize, HttpServletRequest request, HttpServletResponse response) {
		ListObject<CashApply> result = new ListObject<CashApply>();
		try {
			String openId = super.getCurrentLoginOpenId(request, response);
			List<CashApply> applies = cashApplyService.findCashApplyPageByOpenId(openId, pageIndex, pageSize);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setItems(applies);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}
}
